package com.lzh.service.impl;

import com.lzh.consumer.IdempotentEnum;
import com.lzh.domain.entity.UserBackpack;
import com.lzh.exception.ErrorEnum;
import com.lzh.mapper.UserBackpackMapper;
import com.lzh.service.UserBackpackService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.utils.AssertUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户背包表 服务实现类
 * </p>
 *
 * @author lzh
 * @since 2024-09-07
 */
@Service
public class UserBackpackImpl extends ServiceImpl<UserBackpackMapper, UserBackpack> implements UserBackpackService {


    @Lazy
    @Resource
    private UserBackpackService userBackpackService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<UserBackpack> powerBadgeListByUid(Long uid, List<Long> collect) {
        return lambdaQuery()
                .eq(UserBackpack::getUid, uid)
                .in(UserBackpack::getItemId, collect)
                .list();
    }

    @Override
    public void idempotentItem(Long uid, Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        String idempotent = getIdempotent(itemId, idempotentEnum, businessId);
        RLock lock = redissonClient.getLock(idempotent);
        boolean res = lock.tryLock();
        //获取到了锁说明已经有个线程进入了，抛异常
        AssertUtil.isTrue(res, "请求太频繁了");
        try {
            UserBackpack backpackByIdempotent = userBackpackService.getBackpackByIdempotent(idempotent);
            if (Objects.nonNull(backpackByIdempotent)) {
                return;
            }
            UserBackpack build = UserBackpack.builder().idempotent(idempotent)
                    .uid(uid)
                    .itemId(itemId)
                    .status(0)
                    .build();
            userBackpackService.save(build);

        } finally {
            lock.unlock();
        }
    }

    @Override
    public UserBackpack getBackpackByIdempotent(String idempotent) {
        return lambdaQuery()
                .eq(UserBackpack::getIdempotent, idempotent)
                .one();
    }

    private String getIdempotent(Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        return String.format("%d_%d_%s", itemId, idempotentEnum.getType(), businessId);
    }
}
